package net.jxtz.jxtzos.controller.auth;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.auth.Wechat;
import net.jxtz.jxtzos.entity.web.R;
import net.jxtz.jxtzos.service.auth.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author a123
 */
@RestController
@CrossOrigin
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public R add(@RequestBody Wechat wechat){
        Wechat unionId = wechatService.getOne(new QueryWrapper<Wechat>().eq("union_id", wechat.getUnionid()));
        boolean isPresent = Optional.ofNullable(unionId).isPresent();
        if (isPresent){
            return R.ok().data("wechatId", unionId.getId() + "");
        }else {
            boolean save = wechatService.save(wechat);
            return save ? R.ok().data("wechatId", wechat.getId() + ""):R.error();
        }

    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public R add(@PathVariable Long id){
        boolean save = wechatService.removeById(id);
        return save ? R.ok():R.error();
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public R list(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize){
        Page<Wechat> page = wechatService.page(new Page<>(pageNum, pageSize));
        long total = page.getTotal();
        List<Wechat> records = page.getRecords();
        return R.ok().data("total", total).data("list", records);
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public R update(@RequestBody Wechat wechat){
        boolean b = wechatService.updateById(wechat);
        return b ? R.ok():R.error();
    }

    private WechatService wechatService;

    @Autowired
    public void setWechatService(WechatService wechatService){
        this.wechatService = wechatService;
    }
}
